package com.bestcem.xm.user.util.business;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.user.constant.UserCacheKeyConstant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户组织层级锁工具类
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/2/8 16:11
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Component
public class GroupLockUtil {

    @Autowired
    private RedisService redisService;

    /**
     * 对指定的租户添加组织层级锁
     *
     * @param orgId 租户id
     * @return boolean true：锁定成功、false：锁定失败
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/02/08 16:19
     */
    public void lock(String orgId) {
        String lockKey = String.format(UserCacheKeyConstant.USER_GROUP_LEVEL_LOCK_KEY, orgId);
        redisService.setIfAbsent(lockKey, String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 对指定的租户释放组织层级锁
     *
     * @param orgId 租户id
     * @return boolean true：解锁成功、false：解锁失败
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/02/08 16:19
     */
    public void unlock(String orgId) {
        String lockKey = String.format(UserCacheKeyConstant.USER_GROUP_LEVEL_LOCK_KEY, orgId);
        redisService.del(lockKey);
    }

    /**
     * 判断当前租户的组织层级的锁定状态
     *
     * @param orgId 租户id
     * @return boolean true：已被锁定、false：未被锁定
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/02/08 16:20
     */
    public boolean getLockFlag(String orgId) {
        if (!ObjectId.isValid(orgId)) {
            return true;
        }
        String lockKey = String.format(UserCacheKeyConstant.USER_GROUP_LEVEL_LOCK_KEY, orgId);
        Boolean bool = redisService.hasKey(lockKey);
        return null != bool && bool;
    }

}
